/*
 * @Description: 
 * @Author: 黎志恒
 * @LastEditors: 熊伟
 * @Date: 2019-03-22 14:25:57
 * @LastEditTime: 2019-06-25 17:18:24
 */

/**
 * 生成文件对应的模块
 * 
 * @param {*} dirPath 文件夹路径
 */
const generateModules = (files) => {
    const modules = {}
    if(files){
        files.keys().forEach(key => {
            modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
        })
    }
    return modules;
}


/**
 * 所有file
 * 
 */
const allFiles = {
    // page: require.context('./modules/page', false, /\.js$/),
    components: require.context('./modules/components', false, /\.js$/),
    // domain: require.context('./modules/domain', false, /\.js$/),
    // other: require.context('./modules/other', false, /\.js$/)
}

/**
 * 所有module
 * 
 */
const allModules = {
    page: generateModules(allFiles.page),
    components: generateModules(allFiles.components),
    domain: generateModules(allFiles.domain),
    other: generateModules(allFiles.other)
}


/**
 * 根据types获取modules下的多个模块的结构化数据
 * @param {*} types module type
 * @param {*} fieldName 字段名
 */
const getStructuredData = (types, fieldNames) => {
    const structuredData = {};
    types.forEach(type => {
        const modules = allModules[type];
        const structuredModuleData = Object.keys(modules).map(moduleName => {
            const fields = fieldNames.map(fieldName => modules[moduleName][fieldName])
            return {
                [moduleName]: Object.assign(...fields)
            }
        });
        structuredData[type] = structuredModuleData && structuredModuleData.length ? Object.assign(...structuredModuleData) : {};
    })
    return structuredData
}


const enumTypePlugin = store => {

    const mutationTypeEnum = getStructuredData(['page', 'components', 'domain', 'other'], ['mutationTypes']);
    const actionTypeEnum = getStructuredData(['page', 'components', 'domain', 'other'], ['actionTypes']);
    // const getters = getStructuredData(['page', 'components', 'domain', 'other'], ['getters']);
    // const state = getStructuredData(['page', 'components', 'domain', 'other'], ['state']);
    // const mutations = getStructuredData(['page', 'components', 'domain', 'other'], ['mutations']);
    // const actions = getStructuredData(['page', 'components', 'domain', 'other'], ['actions']);
    store.mutationTypes = mutationTypeEnum;
    store.actionTypes = actionTypeEnum;
    // store.state = state;
    // store.getters = getters;
    // store.mutations = mutations;
    // store.actions = actions;
}

export default enumTypePlugin;